<template>
  <div class="checkout-page">
    <div class="checkout-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>确认订单</h2>
      </div>

      <div v-loading="loading" class="checkout-content">
        <!-- 收货地址选择 -->
        <div class="address-section">
          <div class="section-title">
            <span>收货地址</span>
            <el-button type="text" @click="showAddressDialog = true">
              <el-icon>
                <Plus/>
              </el-icon>
              添加新地址
            </el-button>
          </div>

          <div v-if="addresses.length > 0" class="address-list">
            <div
                v-for="address in addresses"
                :key="address.id"
                :class="{ selected: selectedAddressId === address.id }"
                class="address-item"
                @click="selectedAddressId = address.id"
            >
              <div class="address-info">
                <div class="address-header">
                  <span class="receiver-name">{{ address.receiverName }}</span>
                  <span class="receiver-phone">{{ address.receiverPhone }}</span>
                  <el-tag v-if="address.isDefault" size="small" type="success">默认</el-tag>
                </div>
                <div class="address-detail">
                  {{ address.province }} {{ address.city }} {{ address.district }} {{ address.detailAddress }}
                </div>
              </div>
              <div class="address-radio">
                <el-radio :label="address.id" :value="selectedAddressId"/>
              </div>
            </div>
          </div>

          <div v-else class="empty-address">
            <el-empty description="暂无收货地址">
              <el-button type="primary" @click="showAddressDialog = true">添加地址</el-button>
            </el-empty>
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="products-section">
          <div class="section-title">商品信息</div>
          <div class="products-list">
            <div
                v-for="item in cartItems"
                :key="item.id"
                class="product-item"
            >
              <div class="product-image">
                <el-image
                    :alt="item.productName"
                    :src="item.productImage || '/placeholder.jpg'"
                    fit="cover"
                />
              </div>
              <div class="product-info">
                <h4 class="product-name">{{ item.productName }}</h4>
                <div class="product-price">¥{{ formatPrice(item.price || item.unitPrice || item.currentPrice) }}</div>
              </div>
              <div class="product-quantity">
                <span>x{{ item.quantity }}</span>
              </div>
              <div class="product-subtotal">
                ¥{{ formatPrice(item.subtotal || (item.price || item.unitPrice || item.currentPrice) * item.quantity) }}
              </div>
            </div>
          </div>
        </div>

        <!-- 订单备注 -->
        <div class="remark-section">
          <div class="section-title">订单备注</div>
          <el-input
              v-model="orderRemark"
              :maxlength="200"
              placeholder="选填，请输入订单备注"
              show-word-limit
              type="textarea"
          />
        </div>


        <!-- 订单汇总 -->
        <div class="summary-section">
          <div class="summary-item">
            <span>商品总价：</span>
            <span>¥{{ formatPrice(totalAmount) }}</span>
          </div>
          <div class="summary-item">
            <span>运费：</span>
            <span>¥0.00</span>
          </div>
          <div class="summary-total">
            <span>应付总额：</span>
            <span class="total-price">¥{{ formatPrice(totalAmount) }}</span>
          </div>
        </div>
      </div>

      <!-- 底部操作栏 -->
      <div class="checkout-footer">
        <div class="footer-left">
          <span>共{{ cartItems.length }}件商品</span>
          <span class="total-amount">合计：¥{{ formatPrice(totalAmount) }}</span>
        </div>
        <div class="footer-right">
          <el-button @click="goBack">返回购物车</el-button>
          <el-button
              :disabled="!selectedAddressId || submitting"
              :loading="submitting"
              type="primary"
              @click="submitOrder"
          >
            提交订单
          </el-button>
        </div>
      </div>
    </div>

    <!-- 地址添加对话框 -->
    <el-dialog
        v-model="showAddressDialog"
        title="添加收货地址"
        width="500px"
    >
      <el-form
          ref="addressFormRef"
          :model="addressForm"
          :rules="addressRules"
          label-width="100px"
      >
        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model="addressForm.receiverName" placeholder="请输入收货人姓名"/>
        </el-form-item>
        <el-form-item label="手机号" prop="receiverPhone">
          <el-input v-model="addressForm.receiverPhone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="省市区" prop="region">
          <AddressSelector v-model="addressForm.region"/>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input
              v-model="addressForm.detailAddress"
              placeholder="请输入详细地址"
              type="textarea"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddressDialog = false">取消</el-button>
        <el-button :loading="addressSubmitting" type="primary" @click="saveAddress">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import AddressSelector from '@/components/AddressSelector.vue'
import {createOrder} from '@/api/order'
import {createAddress, getUserAddresses} from '@/api/address'
// 路由相关
const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const addressSubmitting = ref(false)
const showAddressDialog = ref(false)
const selectedAddressId = ref(null)

const orderRemark = ref('')
const addresses = ref([])
const cartItems = ref([])

// 地址表单
const addressFormRef = ref()
const addressForm = reactive({
  receiverName: '',
  receiverPhone: '',
  region: '',
  detailAddress: '',
  isDefault: false
})

// 表单验证规则
const addressRules = {
  receiverName: [
    {required: true, message: '请输入收货人姓名', trigger: 'blur'}
  ],
  receiverPhone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
  ],
  region: [
    {required: true, message: '请选择省市区', trigger: 'blur'}
  ],
  detailAddress: [
    {required: true, message: '请输入详细地址', trigger: 'blur'}
  ]
}

// 计算属性
const totalAmount = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + parseFloat(item.subtotal || 0)
  }, 0)
})

// 页面初始化
onMounted(async () => {
  await Promise.all([
    fetchAddresses(),
    loadCartItems()
  ])
})

// 获取地址列表
const fetchAddresses = async () => {
  try {
    const response = await getUserAddresses()
    addresses.value = response.data

    // 自动选择默认地址
    const defaultAddress = addresses.value.find(addr => addr.isDefault)
    if (defaultAddress) {
      selectedAddressId.value = defaultAddress.id
    } else if (addresses.value.length > 0) {
      selectedAddressId.value = addresses.value[0].id
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  }
}

// 加载购物车商品
const loadCartItems = () => {
  try {
    // 从路由参数获取选中的商品
    if (route.query.items) {
      const selectedItems = JSON.parse(route.query.items)
      cartItems.value = selectedItems
      console.log('加载的商品数据:', selectedItems)
    } else {
      console.warn('没有找到商品数据')
      ElMessage.warning('没有找到商品数据，请重新选择商品')
      router.push('/cart')
    }
  } catch (error) {
    console.error('解析商品数据失败:', error)
    ElMessage.error('商品数据格式错误')
    router.push('/cart')
  }
}

// 保存地址
const saveAddress = async () => {
  try {
    await addressFormRef.value.validate()

    addressSubmitting.value = true

    // 解析省市区
    const [province, city, district] = addressForm.region.split(' ')

    const addressData = {
      receiverName: addressForm.receiverName,
      receiverPhone: addressForm.receiverPhone,
      province: province || '',
      city: city || '',
      district: district || '',
      detailAddress: addressForm.detailAddress,
      isDefault: addressForm.isDefault
    }

    await createAddress(addressData)
    ElMessage.success('地址添加成功')

    showAddressDialog.value = false
    Object.assign(addressForm, {
      receiverName: '',
      receiverPhone: '',
      region: '',
      detailAddress: '',
      isDefault: false
    })

    await fetchAddresses()
  } catch (error) {
    if (error !== false) {
      console.error('添加地址失败:', error)
      ElMessage.error('添加地址失败')
    }
  } finally {
    addressSubmitting.value = false
  }
}

// 提交订单
const submitOrder = async () => {
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空')
    return
  }

  try {
    submitting.value = true

    const orderData = {
      addressId: selectedAddressId.value,
      paymentType: 1, // 1-微信支付，2-支付宝支付（默认微信支付）
      remark: orderRemark.value
    }

    // 判断是立即购买还是购物车结算
    const isBuyNow = route.query.type === 'buyNow'

    if (isBuyNow) {
      // 立即购买：使用orderItems
      orderData.orderItems = cartItems.value.map(item => ({
        productId: item.productId,
        quantity: item.quantity
      }))
    } else {
      // 购物车结算：使用cartIds（过滤掉立即购买的临时ID）
      orderData.cartIds = cartItems.value
          .filter(item => !item.id.toString().startsWith('buy_now_'))
          .map(item => item.id)
    }

    // 创建订单
    const response = await createOrder(orderData)
    const orderVO = response.data
    const orderId = orderVO.id

    ElMessage.success('订单创建成功')

    // 跳转到支付页面
    router.push({
      path: `/payment/${orderId}`,
      query: {
        orderNo: orderVO.orderNo,
        totalAmount: orderVO.totalAmount
      }
    })
  } catch (error) {
    console.error('创建订单失败:', error)
    ElMessage.error(error.response?.data?.message || '创建订单失败')
  } finally {
    submitting.value = false
  }
}

// 格式化价格
const formatPrice = (price) => {
  if (price === null || price === undefined || isNaN(price)) {
    return '0.00'
  }
  return parseFloat(price).toFixed(2)
}

// 返回购物车
const goBack = () => {
  router.back()
}
</script>

<style scoped>
.checkout-page {
  min-height: 100vh;
  background: var(--bg-secondary);
  padding: 2rem 0;
}

.checkout-container {
  max-width: 1200px;
  margin: 0 auto;
  background: var(--bg-card);
  border-radius: var(--radius-2xl);
  overflow: hidden;
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--border-light);
}

.page-header {
  padding: 1.5rem 2rem;
  border-bottom: 1px solid var(--border-light);
  background: var(--bg-secondary);
}

.page-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--text-primary);
}

.checkout-content {
  padding: 30px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

/* 地址选择样式 */
.address-section {
  margin-bottom: 30px;
}

.address-list {
  display: grid;
  gap: 15px;
}

.address-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border: 2px solid #ebeef5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #409eff;
}

.address-item.selected {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.address-info {
  flex: 1;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 8px;
}

.receiver-name {
  font-weight: 600;
  color: #303133;
}

.receiver-phone {
  color: #606266;
}

.address-detail {
  color: #909399;
  font-size: 14px;
}

/* 商品信息样式 */
.products-section {
  margin-bottom: 30px;
}

.products-list {
  display: grid;
  gap: 15px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
}

.product-image .el-image {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.product-info {
  flex: 1;
  margin-right: 15px;
}

.product-name {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
}

.product-price {
  color: #f56c6c;
  font-weight: 600;
}

.product-quantity {
  margin-right: 20px;
  color: #606266;
}

.product-subtotal {
  color: #f56c6c;
  font-weight: 600;
  font-size: 16px;
}

/* 其他区域样式 */
.remark-section,
.payment-section {
  margin-bottom: 30px;
}

.summary-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #606266;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.total-price {
  color: #f56c6c;
}

/* 底部操作栏 */
.checkout-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  background: #f8f9fa;
  border-top: 1px solid #ebeef5;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 20px;
  color: #606266;
}

.total-amount {
  font-size: 18px;
  font-weight: 600;
  color: #f56c6c;
}

.footer-right {
  display: flex;
  gap: 15px;
}

/* 响应式设计 */
/* 平板端 */
@media (max-width: 1024px) {
  .checkout-container {
    margin: 0 15px;
  }

  .checkout-content {
    padding: 24px;
  }
}

/* 移动端 */
@media (max-width: 768px) {
  .checkout-container {
    margin: 0 10px;
  }

  .checkout-content {
    padding: 15px;
  }

  .page-header {
    padding: 12px 15px;
  }

  .page-header h2 {
    font-size: 18px;
  }

  .section {
    margin-bottom: 20px;
    border-radius: 8px;
  }

  .section-title {
    font-size: 16px;
    padding: 12px 15px;
  }

  .section-content {
    padding: 15px;
  }

  .address-item {
    padding: 12px;
    margin-bottom: 10px;
  }

  .address-info h4 {
    font-size: 14px;
  }

  .address-info p {
    font-size: 12px;
  }

  .product-item {
    flex-direction: row;
    align-items: center;
    gap: 12px;
    padding: 12px 0;
  }

  .product-image {
    width: 60px;
    height: 60px;
    flex-shrink: 0;
  }

  .product-info {
    flex: 1;
    min-width: 0;
  }

  .product-name {
    font-size: 13px;
    line-height: 1.3;
  }

  .product-price {
    font-size: 14px;
  }

  .payment-methods {
    gap: 10px;
  }

  .payment-method {
    padding: 12px;
  }

  .payment-method .method-name {
    font-size: 14px;
  }

  .checkout-footer {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
    padding: 15px;
  }

  .footer-left {
    justify-content: center;
  }

  .total-amount {
    font-size: 16px;
  }

  .footer-right {
    justify-content: center;
    gap: 10px;
  }

  .footer-right .el-button {
    flex: 1;
    font-size: 14px;
  }
}

/* 小屏手机 */
@media (max-width: 480px) {
  .checkout-container {
    margin: 0 8px;
  }

  .checkout-content {
    padding: 12px;
  }

  .page-header {
    padding: 10px 12px;
  }

  .page-header h2 {
    font-size: 16px;
  }

  .section-title {
    font-size: 15px;
    padding: 10px 12px;
  }

  .section-content {
    padding: 12px;
  }

  .address-item {
    padding: 10px;
  }

  .product-item {
    gap: 10px;
    padding: 10px 0;
  }

  .product-image {
    width: 50px;
    height: 50px;
  }

  .product-name {
    font-size: 12px;
  }

  .product-price {
    font-size: 13px;
  }

  .payment-method {
    padding: 10px;
  }

  .checkout-footer {
    padding: 12px;
  }

  .total-amount {
    font-size: 15px;
  }

  .footer-right .el-button {
    font-size: 13px;
    padding: 8px 16px;
  }
}
</style>
